<?php
/**
 * Created by PhpStorm.
 * User: jinqiang
 * Date: 2019/8/5
 * Time: 20:19
 */

namespace App\Http\Repository;


use Carbon\Carbon;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Storage;
use Intervention\Image\Facades\Image;
use TCPDF;

class CommonRepository
{
    CONST CATEGORY = [1 => "主料", 2 => "辅料", 3 => "特殊工艺"];

    CONST ATTRIBUTE = '[
        {"id": 0, "name": "通用"},
        {"id": 6, "name": "通用（分码）"},
        {"id": 1, "name": "布匹"},
        {"id": 7, "name": "针织布"},
        {"id": 5, "name": "布匹（固定门幅）"},
        {"id": 2, "name": "拉链"},
        {"id": 3, "name": "成品螺纹"},
        {"id": 4, "name": "尺码标"},
        {"id": 8, "name": "线"}]';

    CONST ATTRIBUTE_DETAIL = '{
        "0": [
            {"id": 1,"name": "固定规格","type": "NORMAL","inputType": "TEXT","category": "PRIMARY","scale": 0,"min": 0,"max": 0,"re": "","value": "","default": ""},
            {"id": 2,"name": "采购规格","type": "NORMAL","inputType": "TEXT","category": "CUSTOM","scale": 0,"min": 0,"max": 0,"re": "","value": "","default": ""}
        ],
        "1": [
            {"id": 1,"name": "针/梭织","type": "NORMAL","inputType": "LIST","category": "PRIMARY","scale": 0,"min": 0,"max": 0,"re": "","value": ["针织","梭织"],"default": ""},
            {"id": 2,"name": "门幅(cm)","type": "NORMAL","inputType": "NUMBER","category": "CUSTOM","scale": 0,"min": 1,"max": 500,"re": "","value": "","default": ""},
            {"id": 3,"name": "纱支","type": "NORMAL","inputType": "TEXT","category": "PRIMARY","scale": 0,"min": 0,"max": 0,"re": "","value": "","default": ""},
            {"id": 4,"name": "密度","type": "NORMAL","inputType": "TEXT","category": "PRIMARY","scale": 0,"min": 0,"max": 0,"re": "","value": "","default": ""},
            {"id": 5,"name": "克重","type": "NORMAL","inputType": "TEXT","category": "PRIMARY","scale": 0,"min": 0,"max": 0,"re": "","value": "","default": ""},
            {"id": 6,"name": "成分","type": "NORMAL","inputType": "TEXT","category": "PRIMARY","scale": 0,"min": 0,"max": 0,"re": "","value": "","default": ""},
            {"id": 7,"name": "其他","type": "NORMAL","inputType": "TEXT","category": "CUSTOM","scale": 0,"min": 0,"max": 0,"re": "","value": "","default": ""}
        ],
        "2": [
            {"id": 1,"name": "带拉头","type": "NORMAL","inputType": "BOOL","category": "PRIMARY","scale": 0,"min": 0,"max": 0,"re": "","value": "","default": ""},
            {"id": 2,"name": "拉头","type": "NORMAL","inputType": "TEXT","category": "PRIMARY","scale": 0,"min": 0,"max": 0,"re": "","value": "","default": ""},
            {"id": 3,"name": "织带色","type": "COLOUR","inputType": "TEXT","category": "CUSTOM","scale": 0,"min": 0,"max": 0,"re": "","value": "","default": ""},
            {"id": 4,"name": "长度(cm)","type": "SIZE","inputType": "NUMBER","category": "CUSTOM","scale": 2,"min": 1,"max": 200,"re": "","value": "","default": ""},
            {"id": 5,"name": "拉齿","type": "NORMAL","inputType": "TEXT","category": "PRIMARY","scale": 0,"min": 0,"max": 0,"re": "","value": "","default": ""},
            {"id": 6,"name": "拉头色","type": "COLOUR","inputType": "TEXT","category": "CUSTOM","scale": 0,"min": 0,"max": 0,"re": "","value": "","default": ""},
            {"id": 7,"name": "其他","type": "NORMAL","inputType": "TEXT","category": "CUSTOM","scale": 0,"min": 0,"max": 0,"re": "","value": "","default": ""}
        ],
        "3": [
            {"id": 1,"name": "克重","type": "NORMAL","inputType": "TEXT","category": "PRIMARY","scale": 0,"min": 0,"max": 0,"re": "","value": "","default": ""},
            {"id": 2,"name": "尺寸","type": "SIZE","inputType": "TEXT","category": "CUSTOM","scale": 0,"min": 0,"max": 0,"re": "","value": "","default": ""}
        ],
        "4": [
            {"id": 1,"name": "固定规格","type": "NORMAL","inputType": "TEXT","category": "PRIMARY","scale": 0,"min": 0,"max": 0,"re": "","value": "","default": ""},
            {"id": 2,"name": "采购规格","type": "NORMAL","inputType": "TEXT","category": "CUSTOM","scale": 0,"min": 0,"max": 0,"re": "","value": "","default": ""},
            {"id": 3,"name": "尺寸","type": "SIZE","inputType": "TEXT","category": "CUSTOM","scale": 0,"min": 0,"max": 0,"re": "","value": "","default": ""}
        ],
        "5": [
            {"id": 1,"name": "针/梭织","type": "NORMAL","inputType": "LIST","category": "PRIMARY","scale": 0,"min": 0,"max": 0,"re": "","value": ["针织","梭织"],"default": ""},
            {"id": 2,"name": "门幅(cm)","type": "NORMAL","inputType": "NUMBER","category": "CUSTOM","scale": 0,"min": 1,"max": 500,"re": "","value": "","default": ""},
            {"id": 3,"name": "纱支","type": "NORMAL","inputType": "TEXT","category": "PRIMARY","scale": 0,"min": 0,"max": 0,"re": "","value": "","default": ""},
            {"id": 4,"name": "密度","type": "NORMAL","inputType": "TEXT","category": "PRIMARY","scale": 0,"min": 0,"max": 0,"re": "","value": "","default": ""},
            {"id": 5,"name": "克重","type": "NORMAL","inputType": "TEXT","category": "PRIMARY","scale": 0,"min": 0,"max": 0,"re": "","value": "","default": ""},
            {"id": 6,"name": "成分","type": "NORMAL","inputType": "TEXT","category": "PRIMARY","scale": 0,"min": 0,"max": 0,"re": "","value": "","default": ""}
        ],
        "6": [
            {"id": 1,"name": "固定规格","type": "NORMAL","inputType": "TEXT","category": "PRIMARY","scale": 0,"min": 0,"max": 0,"re": "","value": "","default": ""},
            {"id": 2,"name": "采购规格","type": "NORMAL","inputType": "TEXT","category": "CUSTOM","scale": 0,"min": 0,"max": 0,"re": "","value": "","default": ""},
            {"id": 3,"name": "尺寸","type": "SIZE","inputType": "TEXT","category": "CUSTOM","scale": 0,"min": 0,"max": 0,"re": "","value": "","default": ""}
        ],
        "7": [
            {"id": 1,"name": "门幅(cm)","type": "NORMAL","inputType": "NUMBER","category": "CUSTOM","scale": 0,"min": 1,"max": 500,"re": "","value": "","default": ""},
            {"id": 2,"name": "纱支","type": "NORMAL","inputType": "TEXT","category": "PRIMARY","scale": 0,"min": 0,"max": 0,"re": "","value": "","default": ""},
            {"id": 3,"name": "密度","type": "NORMAL","inputType": "TEXT","category": "PRIMARY","scale": 0,"min": 0,"max": 0,"re": "","value": "","default": ""},
            {"id": 4,"name": "克重(g/m²)","type": "NORMAL","inputType": "NUMBER","category": "CUSTOM","scale": 0,"min": 1,"max": 800,"re": "","value": "","default": ""},
            {"id": 5,"name": "成分","type": "NORMAL","inputType": "TEXT","category": "PRIMARY","scale": 0,"min": 0,"max": 0,"re": "","value": "","default": ""}
        ],
        "8": [
            {"id": 1,"name": "规格","type": "NORMAL","inputType": "TEXT","category": "PRIMARY","scale": 0,"min": 0,"max": 0,"re": "","value": "","default": ""},
            {"id": 2,"name": "成分","type": "NORMAL","inputType": "TEXT","category": "PRIMARY","scale": 0,"min": 0,"max": 0,"re": "","value": "","default": ""},
            {"id": 3,"name": "其他","type": "NORMAL","inputType": "TEXT","category": "CUSTOM","scale": 0,"min": 0,"max": 0,"re": "","value": "","default": ""},
            {"id": 4,"name": "转换率","type": "NORMAL","inputType": "NUMBER","category": "CUSTOM","scale": 2,"min": 0.01,"max": 10000,"re": "","value": "","default": ""}
        ]
    }';

    //删除cdn静态资源服务器 oss
    public static function delectCDN($url, $type = 'style')
    {
        try {
            //指定存储磁盘
            $disk = Storage::disk($type);
            $urlArr = parse_url($url);
            $fileName = $urlArr['path'];
            $res = $disk->delete($fileName);
            return $res ? ['code' => 0, 'msg' => '删除图片成功'] : ['code' => -1, 'msg' => '删除图片失败'];
        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
        return ['code' => -1, 'msg' => "删除图片失败"];
    }

    //上传cdn静态资源服务器 oss
    public static function uploadCDN($url, $type = 'image', $name = '', $content = "")
    {
        try {
            //指定存储磁盘
            $disk = Storage::disk($type);
            $extension = pathinfo($url, PATHINFO_EXTENSION) ?: (pathinfo($name, PATHINFO_EXTENSION) ?: "jpg");
            $name = str_replace(".{$extension}", "", $name);
            $fileName = "{$type}/" . ($name ?: md5($url)) . ".{$extension}";
            $cdnDomain = env('ALIYUN_CDN_DOMAIN');
            $imgFile = $cdnDomain . $fileName;
            if (str_starts_with($url, $cdnDomain)) {
                return ['code' => 0, 'file' => $url, 'msg' => 'exists'];
            }
            if ($disk->exists($fileName)) {
                return ['code' => 0, 'file' => $imgFile, 'msg' => 'exists'];
            }
            if (str_starts_with($url, "http")) {
                $urlArr = parse_url($url);
                $form = [
                    'timeout' => 3,
                    'base_uri' => $urlArr['scheme'] . "://" . $urlArr['host'],
                    'form_params' => []
                ];
                $content = httpClient($url, $form);
            } elseif(empty($content)) {
                $content = file_get_contents($url);
            }
            if (empty($content)) {
                return ['code' => -1, 'msg' => "获取链接内容失败"];
            }
            $isPut = $disk->put($fileName, $content);
            if ($isPut) {
                return ['code' => 0, 'file' => $imgFile];
            }
        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
        return ['code' => -1, 'msg' => "保存图片失败"];
    }

    //生成缩略图
    public static function thumbImg($url, $type = "style", $name = "", $width = 150, $height = 150)
    {
        $extension = pathinfo($url, PATHINFO_EXTENSION) ?: "jpg";
        $savePath = storage_path("cache/");
        $imgFile = $savePath.($name ?: md5($url)) . ".{$extension}";
        try{
            Image::make($url)->resize($width, $height, function ($constraint) {
                $constraint->aspectRatio(); // 保持宽高比
                $constraint->upsize(); // 防止放大图片
            })->save($imgFile);
            $res = self::uploadCDN($imgFile, $type, $name);
            unlink($imgFile);
            return $res;
        }catch (\Exception $e){
            @unlink($imgFile);
            return ['code' => -1, 'msg' => "图片处理失败", 'data' => $e->getMessage()];
        }
        return ['code' => -1, 'msg' => "图片处理失败"];
    }

    //浏览器下载文件
    public static function downFile($url, $filename = "", $type = "url")
    {
        $filename = $filename ?: basename($url);
        if($type == "url"){
            $headers = get_headers($url, 1);
            $fileSize = $headers['Content-Length'];
        }else{
            $fileSize = filesize($url);
        }
        header('Content-Type: application/octet-stream');
        header('Accept-Ranges:bytes');
        header('Content-Length: ' . $fileSize);
        header('Content-Disposition: attachment; filename="' . $filename . '"');
        readfile($url);
        exit;
    }

    //导出pdf
    public static function downPdf($filename, $title, $html = "")
    {
        $pdf = new TCPDF();
        $pdf->SetTitle($title);
        $pdf->SetSubject('TCPDF Tutorial');
        $pdf->SetKeywords('TCPDF, PDF, PHP');
        // 设置页眉和页脚信息
        $pdf->setFooterData(array(0,64,0), array(0,64,128));
        // 设置页眉和页脚字体
        $pdf->setHeaderFont(Array('stsongstdlight', '', '10'));
        $pdf->setFooterFont(Array('helvetica', '', '8'));
        // 设置间距
        $pdf->SetMargins(5, 27, 5);
        $pdf->SetHeaderMargin(5);
        $pdf->SetFooterMargin(10);
        // 设置分页
        $pdf->SetAutoPageBreak(TRUE, 25);
        // set image scale factor
        $pdf->setImageScale(1.25);
        // set default font subsetting mode
        $pdf->setFontSubsetting(true);
        //设置字体
        $pdf->SetFont('stsongstdlight', '', 14);
        $pdf->AddPage();
        $pdf->writeHTML($html);

        $pdf->Output($filename);
    }

    //将颜色code 转换成 颜色编码 十进制转换成16进制
    public static function getColor($code)
    {
        $red = ($code >> 16) & 0xFF; // 提取红色部分
        $green = ($code >> 8) & 0xFF; // 提取绿色部分
        $blue = $code & 0xFF; // 提取蓝色部分

        $hexColor = sprintf("#%02X%02X%02X", $red, $green, $blue);
        return $hexColor; // 输出 #9A32B0
    }

    //将颜色码 转换成 十进制
    public static function setColor($color)
    {
        // 移除颜色码开头的 # 符号
        $hexColor = ltrim($color, '#');
        // 将十六进制颜色码转换为十进制数
        $decimalColor = hexdec($hexColor);
        return $decimalColor;
    }

    //客户端ip访问限制
    public static function detectClientId($clientId, $num = 10)
    {
        info("CLIENT_IP", [$clientId]);
        $requestNum = Cache::get($clientId) ?: 1;
        if($requestNum > $num){
            return ['code'=>-1, 'msg' => "操作过于频繁"];
        }else{
            $requestNum += 1;
            Cache::put($clientId, $requestNum, Carbon::now()->addMinutes(30));
        }
        return ['code'=> 0];
    }
}
